package com.zznj.xzjc.fragment.index;

import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.SimpleItemAnimator;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.vondear.rxtool.RxActivityTool;
import com.vondear.rxui.fragment.NewLazyFragment;
import com.zznj.xzjc.R;
import com.zznj.xzjc.activity.index.IndexWebActivity;
import com.zznj.xzjc.activity.index.work.ActivityWorkMain;
import com.zznj.xzjc.adapter.index.WorkAdapter;
import com.zznj.xzjc.event.EventTag;
import com.zznj.xzjc.event.MessageEvent;
import com.zznj.xzjc.net.SharedHelper;
import com.zznj.xzjc.net.entity.BaseBean;
import com.zznj.xzjc.net.entity.IndexNewXianSuoBean;
import com.zznj.xzjc.net.entity.LoginBean;
import com.zznj.xzjc.net.rxjava.HttpMethods;
import com.zznj.xzjc.net.subscribers.ProgressSubscriber;
import com.zznj.xzjc.net.subscribers.SubscriberOnNextListener;
import com.zznj.xzjc.utils.StringUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import okhttp3.FormBody;

import static com.zznj.xzjc.net.rxjava.HttpMethods.BASE_WORK_URL;

/**
 * 描述：知识库
 */
public class WorkFragment extends NewLazyFragment implements BaseQuickAdapter.OnItemClickListener {
    @BindView(R.id.rec_main)
    RecyclerView recMain;
    @BindView(R.id.srl_all)
    SmartRefreshLayout srlAll;
    @BindView(R.id.tishiImg)
    ImageView tishiImg;
    @BindView(R.id.bottomLinear)
    View bottomLinear;
    Unbinder unbinder;
    private String searchType;

    public static WorkFragment getInstance(String searchType, String key) {
        WorkFragment fragment = new WorkFragment();
        fragment.searchType = searchType;
        return fragment;
    }

    @Override
    protected int getContentViewId() {
        return R.layout.gyss_fragment_index_work_layout;
    }

    private LoginBean user;

    public void search() {
        refresh(true);
    }

    @Override
    protected void initView(View view) {
        unbinder = ButterKnife.bind(this, view);
        user = new Gson().fromJson(SharedHelper.readValueByKeyForString(mContext, "Member"), LoginBean.class);

        init();
        initSrl();
        super.initView(view);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void refreshData(MessageEvent messageEvent) {
        if (messageEvent.getTag().equals(EventTag.DT)) {
            refresh(true);
        }
    }

    public void refresh(boolean isShowDialog) {
        isShowDialog = isShowDialog;
        page = 1;
        srlAll.setEnableLoadMore(true);
        mList.clear();
        bottomLinear.setVisibility(View.GONE);
        mAdapter.notifyDataSetChanged();
        getData();
    }


    private void initSrl() {
        srlAll.setEnableRefresh(true);
        srlAll.setEnableLoadMore(true);
        srlAll.setOnRefreshListener(refresh_layout -> {
            refresh(false);
        });
        srlAll.setOnLoadMoreListener(refresh_layout -> {
            isShowDialog = false;
            page++;
            getData();
        });
    }

    private List<IndexNewXianSuoBean> mList;
    private WorkAdapter mAdapter;

    private void init() {
        mList = new ArrayList<>();
        ((SimpleItemAnimator) recMain.getItemAnimator()).setSupportsChangeAnimations(false);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mContext);
        recMain.setLayoutManager(linearLayoutManager);
        mAdapter = new WorkAdapter(R.layout.gyss_item_work, mList,searchType);
        recMain.setAdapter(mAdapter);
        mAdapter.setOnItemClickListener(this);
    }

    private int page = 1;
    private boolean isShowDialog = true;

    @Override
    protected void initData() {
        getData();
    }

    private void getData() {
        SubscriberOnNextListener<BaseBean> onNextListener = baseBean -> {
            if(srlAll != null){
                srlAll.finishLoadMore();
                srlAll.finishRefresh();
            }
            if (baseBean.isSuccess()) {
                String data = baseBean.getMessage();
                if (!StringUtils.isEmpty(data)) {
                    Map<String, String> dataMap = new Gson().fromJson(data, new TypeToken<Map<String, String>>() {
                    }.getType());
                    String solrDocumentList = dataMap.get("solrDocumentList");
                    if (!StringUtils.isEmpty(solrDocumentList)) {
                        List<IndexNewXianSuoBean> sdList = new Gson().fromJson(solrDocumentList, new TypeToken<List<IndexNewXianSuoBean>>() {
                        }.getType());
                        if(mList.size() + sdList.size() > 0 && sdList.size() < 10){
                            bottomLinear.setVisibility(View.VISIBLE);
                            if(srlAll != null){
                                srlAll.setEnableLoadMore(false);
                            }
                        }
                        mAdapter.addData(sdList);
                    }
                }
            }
//            mAdapter.notifyDataSetChanged();
            mAdapter.setKey(((ActivityWorkMain)getActivity()).getKey());
            if(mAdapter.getItemCount() == 0){
                tishiImg.setVisibility(View.VISIBLE);
                srlAll.setVisibility(View.GONE);
                if(!StringUtils.isEmpty(((ActivityWorkMain)getActivity()).getKey())){
                    tishiImg.setImageResource(R.mipmap.gyss_wjsjg_img);
                }else{
                    tishiImg.setImageResource(R.mipmap.gyss_zwnr_img);
                }
            }else{
                tishiImg.setVisibility(View.GONE);
                srlAll.setVisibility(View.VISIBLE);
            }
        };

        if(mList.size() == 0){
            page = 1;
        }

        Map<String, Object> paramsMap = new HashMap<>();
        paramsMap.put("Q_sourceName_s_S", "");
        paramsMap.put("classType_s", "");
        paramsMap.put("publishTime_date", "");
        paramsMap.put("page",page+"");
        paramsMap.put("rows","10");

        String searchParam = new Gson().toJson(paramsMap);
        FormBody requestBody = new FormBody.Builder()
                .add("searchType", searchType)
                .add("searchParam", searchParam)
                .add("searchWord", ((ActivityWorkMain)getActivity()).getKey())
                .build();
        HttpMethods.getInstance().getFindXianSuoList(new ProgressSubscriber<>(onNextListener, mContext, isShowDialog), requestBody);
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
        unbinder.unbind();
    }

    @Override
    public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
        IndexNewXianSuoBean item = mList.get(position);
//        Bundle bundle = new Bundle();
//        bundle.putString("id",mList.get(position).getId_l()+"");
//        bundle.putString("caseType",searchType);
//        RxActivityTool.skipActivity(getContext(), ActivityWorkDetail.class,bundle);

        String lx = "";
        if("9".equals(item.getDataType_i())){
            lx = "工作动态";
        }else if("12".equals(item.getDataType_i())){
            lx = "产品召回";
        }else if("11".equals(item.getDataType_i())){
            lx = "政策发布";
        }else if("10".equals(item.getDataType_i())){
            lx = "案例播报";
        }else if("15".equals(item.getDataType_i())){
            lx = "通知公告";
        }

        Bundle bundle = new Bundle();
        bundle.putString("path", BASE_WORK_URL+item.getId_l()+"&userId="+user.getUserId());
        bundle.putString("title", lx+"详情");

        bundle.putString("contentTitle", item.getIndexTitle_s());
        bundle.putString("collectType", "notice");
        bundle.putString("infoSign", searchType);
        bundle.putString("fromActivity", "0");
        bundle.putString("id", item.getId_l()+"");

        RxActivityTool.skipActivity(mContext, IndexWebActivity.class,bundle);
    }
}